package com.jeesuite.bestpl.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jeesuite.bestpl.dao.entity.UserEntity;
import com.jeesuite.bestpl.dto.Constants;
import com.jeesuite.bestpl.dto.PageMetaInfo;
import com.jeesuite.bestpl.exception.JeesuiteBaseException;
import com.jeesuite.bestpl.oauth2.OauthConnector;
import com.jeesuite.bestpl.oauth2.OauthUser;
import com.jeesuite.bestpl.oauth2.connector.GithubConnector;
import com.jeesuite.bestpl.oauth2.connector.OSChinaConnector;
import com.jeesuite.bestpl.oauth2.connector.QQConnector;
import com.jeesuite.bestpl.oauth2.connector.WechatConnector;
import com.jeesuite.bestpl.oauth2.connector.WeiboConnector;
import com.jeesuite.bestpl.security.LoginUserInfo;
import com.jeesuite.bestpl.service.UserService;



@Controller
@RequestMapping("/oauth2")
public class SnsOauth2Controller implements EnvironmentAware{
	
	private Map<String, OauthConnector> oauthConnectors = new HashMap<>();
	
	private @Autowired UserService userService;
	
	@RequestMapping(value = "{type}", method = RequestMethod.GET)
	public String redirect(HttpServletRequest request,@PathVariable("type") String type){
		
		OauthConnector connector = oauthConnectors.get(type);
		if(connector == null)throw new JeesuiteBaseException("不支持授权类型:"+type);
		
		String state = UUID.randomUUID().toString().replaceAll("-", "");
		String callBackUrl = request.getRequestURL().toString().replace("/" + type, "/callback/" + type);
		String url = connector.getAuthorizeUrl(state, callBackUrl);
		
		request.getSession().setAttribute("oauth_state", state);
		return "redirect:" + url; 
	}
	
	@RequestMapping(value = "callback/{type}", method = {RequestMethod.GET,RequestMethod.POST})
	public String callback(HttpServletRequest request,Model model,@PathVariable("type") String type) {
		String code = request.getParameter("code");
		String stateIn = request.getParameter("state");
		
		Object state = request.getSession().getAttribute("oauth_state");
		
		request.getSession().removeAttribute("oauth_state");
		if(state == null || !StringUtils.equalsIgnoreCase(stateIn, state.toString())){
			return "redirect:/index"; 
		}
		
		OauthConnector connector = oauthConnectors.get(type);
		
		OauthUser oauthUser = connector.getUser(code);
		//根据openid 找用户，
		UserEntity userEntity = userService.findUserbyOpenIdAndType(type, oauthUser.getOpenId());
		
		if(userEntity != null){
			LoginUserInfo loginUserInfo = new LoginUserInfo(userEntity.getId(),userEntity.getNickname(),userEntity.getUserType());
			loginUserInfo.setAvatar(userEntity.getAvatar());
			request.getSession().setAttribute(Constants.LOGIN_SESSION_KEY, loginUserInfo);
			return "redirect:/ucenter/index"; 
		}
		
		//跳转去绑定页面
		model.addAttribute(PageMetaInfo.ATTR_NAME, PageMetaInfo.current().setModelName("user"));
		model.addAttribute("oauthUser", oauthUser);
		//
		request.getSession().setAttribute("oauth_openid", type + ":" +state);
		
		return "user/bind"; 
	}

	@Override
	public void setEnvironment(Environment environment) {
		RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment, "oauth.");
		Map<String, Object> subProperties = resolver.getSubProperties("");
		String type;String appKey;String appSecret;
		for (String key : subProperties.keySet()) {
			type = key.split("\\.")[1];
			if(oauthConnectors.containsKey(type))continue;
			appKey = environment.getProperty("oauth."+type+".appkey");
			appSecret = environment.getProperty("oauth."+type+".appSecret");
			
			if(QQConnector.SNS_TYPE.equals(type)){				
				oauthConnectors.put(type, new QQConnector(appKey, appSecret));
			}else if(GithubConnector.SNS_TYPE.equals(type)){				
				oauthConnectors.put(type, new GithubConnector(appKey, appSecret));
			}else if(OSChinaConnector.SNS_TYPE.equals(type)){				
				oauthConnectors.put(type, new OSChinaConnector(appKey, appSecret));
			}else if(WechatConnector.SNS_TYPE.equals(type)){				
				oauthConnectors.put(type, new WechatConnector(appKey, appSecret));
			}else if(WeiboConnector.SNS_TYPE.equals(type)){				
				oauthConnectors.put(type, new WeiboConnector(appKey, appSecret));
			}
			
		}
		
	}

}
